package h0826;

import java.util.List;
import java.util.PriorityQueue;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 合并k个有序链表
 * @date 2024/8/26 12:41
 */
public class MergeKLists {

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1, new ListNode(4, new ListNode(5)));
        ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        ListNode l3 = new ListNode(2, new ListNode(6));
        ListNode[] listNodes = new ListNode[3];
        listNodes[0] = l1;
        listNodes[1] = l2;
        listNodes[2] = l3;
        ListNode res = mergeKLists(listNodes);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }

        ListNode ans = lists[0];
        for (int i = 1; i < lists.length; i++) {
            ans = margetTwoLists(ans, lists[i]);
        }

        return ans;
    }

    private static ListNode margetTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode pre = dummy;

        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                pre.next = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                l2 = l2.next;
            }
            pre = pre.next;
        }
        if (l1 != null) {
            pre.next = l1;
        }
        if (l2 != null) {
            pre.next = l2;
        }
        return dummy.next;
    }

    //使用最小堆的方法，每次出来必定是最小的。
    private static ListNode mergeKLists2(ListNode[] lists) {

        if (lists == null || lists.length == 0) {
            return null;
        }

        PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);

        // 初始化堆
        for (ListNode list : lists) {
            if (list != null) {
                //将每个元素的头节点加入进来
                minHeap.offer(list);
            }
        }

        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

       while (!minHeap.isEmpty()){
           ListNode node = minHeap.poll();
           current.next=node;
           current=current.next;
           if (node.next!=null){
               minHeap.offer(node.next);
           }
       }

        return dummy.next;
    }
}
